package com.zero.manage.web.utils.generate;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.zero.manage.web.components.entity.DatabaseInfoEntity;
import io.gitee.zerowsh.enums.ToolEnums;
import com.zero.manage.web.utils.generate.service.MysqlService;
import com.zero.manage.web.utils.generate.service.SqlServerService;
import io.gitee.zerowsh.config.SpringContextUtils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;

/**
 * 操作数据库接口定义
 *
 * @author zero
 */
public interface DatabaseDao {
    /**
     * 获取数据库名称
     *
     * @return
     */
    List<String> getCatalogs();

    /**
     * 获取数据库表信息
     *
     * @return
     */
    List<Map<Object, Object>> getTableInfo(String catalogs);

    List<ColumnInfo> getColumns(String catalogs, String tableName);

    static DatabaseDao handleDataSource(DynamicRoutingDataSource ds, String sourceId) {
        DruidDataSource dataSource = (DruidDataSource) ds.getDataSource(sourceId);
        String dbType = dataSource.getDbType();
        if (Objects.equals(dbType, "mysql")) {
            return SpringContextUtils.getBean(MysqlService.class);
        } else if (Objects.equals(dbType, "sqlserver")) {
            return SpringContextUtils.getBean(SqlServerService.class);
        } else {
            //默认mysql
            return SpringContextUtils.getBean(MysqlService.class);
        }
    }

    /**
     * 获取数据库连接
     *
     * @param dataInfo
     * @return
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    static Connection getConnection(DatabaseInfoEntity dataInfo) throws SQLException, ClassNotFoundException {
        ToolEnums.DataBaseTypeEnums type = dataInfo.getDatabaseType();
        Class.forName(ToolEnums.DataBaseEnums.getDriver(type));
        Properties props = new Properties();
        props.setProperty("user", dataInfo.getUsername());
        props.setProperty("password", dataInfo.getPassword());
        String url = ToolEnums.DataBaseEnums.getUrlPrefixByKey(type) + dataInfo.getIpPort() + dataInfo.getOtherParams();
        return DriverManager.getConnection(url, props);
    }

}
